<template>
  <div class="login-container">
    <!-- logo -->
    <div class="login-logo">
      <svg-icon icon-class="logo"></svg-icon>
      2025重庆市城市体检信息平台
    </div>

    <!-- login form -->
    <div class="login-form">
      <div class="login-title">用户登录</div>
      <el-form
        :model="loginForm"
        :label-position="'left'"
        :rules="rules"
        ref="loginForm"
        class="login-box"
        label-width="70px"
      >
        <el-form-item label="用户名：" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            @keyup.enter.native="handleSubmit"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="">
          <div class="login-extent">
            <div>
              <el-checkbox v-model="loginForm.remember"
                >记住用户名和密码</el-checkbox
              >
            </div>
            <div>没有账号？去注册</div>
          </div>
        </el-form-item> -->
        <el-button
          type="primary"
          class="submit-btn"
          @click.stop.prevent="handleSubmit"
          >登录</el-button
        >
      </el-form>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="changePasswordDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form
        :model="changePasswordForm"
        :rules="changePasswordRules"
        ref="changePasswordForm"
        label-width="100px"
      >
        <el-form-item label="修改密码：" prop="password">
          <el-input
            v-model="changePasswordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmPassword">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
             <div slot="footer" class="dialog-footer">
         <el-button @click="cancelChangePassword">取消</el-button>
         <el-button type="primary" @click="confirmChangePassword">确认</el-button>
       </div>
    </el-dialog>
  </div>
</template>

<script>
import cache from '@/utils/cache'
import { changeUserPassword } from '@/api/back-management/user'
import { Base64 } from 'js-base64'

export default {
  name: 'login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        remember: false,
      },
      changePasswordForm: {
        password: '',
        confirmPassword: '',
      },
      changePasswordDialogVisible: false,
      permissionButtonList: [],
      rules: {
        username: [{ validator: this.validatorUsername, trigger: 'blur' }],
        password: [{ validator: this.validatorPassword, trigger: 'blur' }],
      },
      changePasswordRules: {
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', message: '请再次输入您的密码' },
          { required: true, validator: this.validatorConfirmPassword, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    validatorUsername(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    },
    validatorPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    },
    validatorConfirmPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.changePasswordForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    handleSubmit() {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          this.$store
            .dispatch('login', this.loginForm)
            .then(() => {
              const user = cache.getItem('user')
              const permission = JSON.parse(user)?.user?.moduleTree
              const buttonList = JSON.parse(user)?.user?.buttonList
              const passwordStatus = JSON.parse(user)?.user?.passwordStatus
              
              // 检查密码状态，如果不等于1，需要修改密码
              if (passwordStatus !== '1') {
                this.changePasswordDialogVisible = true
                return
              }
              
              // 密码状态正常，进行权限判断和跳转
              this.handlePermissionAndRedirect(permission, buttonList)
            })
            .catch((e) => {
              console.log('e :>> ', e)
              this.$message.error(e)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    
    // 处理权限判断和跳转
    handlePermissionAndRedirect(permission, buttonList) {
      if (permission && permission.length) {
        cache.setItem('city-permission', JSON.stringify(permission))
        this.permissionButtonList = []
        this.setPermissionButtonList(buttonList)
        cache.setItem(
          'city-permissionButtonList',
          JSON.stringify(this.permissionButtonList)
        )
        this.$router.replace({ path: '/home' })
      } else {
        this.$message.error('该账号未配置权限')
      }
    },
    
    // 确认修改密码
    confirmChangePassword() {
      this.$refs['changePasswordForm'].validate((valid) => {
        if (valid) {
          const user = cache.getItem('user')
          const userId = JSON.parse(user)?.user?.pkid
          
          if (!userId) {
            this.$message.error('用户信息获取失败')
            return
          }
          
          const params = {
            userId: userId,
            password: Base64.encode(this.changePasswordForm.password),
          }
          
          changeUserPassword(params)
             .then((res) => {
               if (res.success) {
                 this.$message.success('密码修改成功，请重新登录')
                 this.changePasswordDialogVisible = false
                 this.changePasswordForm.password = ''
                 this.changePasswordForm.confirmPassword = ''
                 
                 // 修改成功后，调用logout退出登录
                 this.$store.dispatch('logout').then(() => {
                   const currentUsername = this.loginForm.username
                   this.loginForm.password = ''
                   this.loginForm.username = currentUsername
                   this.changePasswordForm.password = ''
                   this.changePasswordForm.confirmPassword = ''
                   cache.removeItem('user')
                   this.$nextTick(() => {
                     if (this.$refs.changePasswordForm) {
                       this.$refs.changePasswordForm.clearValidate()
                     }
                     if (this.$refs.loginForm) {
                       this.$refs.loginForm.clearValidate()
                     }
                   })
                   // 提示用户需要重新登录
                  //  this.$message.info('请使用新密码重新登录')
                 })
               } else {
                 this.$message.error(res.message || '密码修改失败')
               }
             })
            .catch((e) => {
              console.log('修改密码失败:', e)
              this.$message.error('密码修改失败')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
         },
     
     // 取消修改密码
     cancelChangePassword() {
       this.changePasswordDialogVisible = false
       this.changePasswordForm.password = ''
       this.changePasswordForm.confirmPassword = ''
       // 重置表单验证状态
       this.$nextTick(() => {
         if (this.$refs.changePasswordForm) {
           this.$refs.changePasswordForm.clearValidate()
         }
       })
     },
     
     setPermissionButtonList(tree) {
      tree.forEach((item) => {
        if (
          item.children.length &&
          item.catalogType === '1' &&
          item.hasPri &&
          item.status === 1
        ) {
          this.setPermissionButtonList(item.children)
        }
        // if (item.children.length) {
        //   item.children = this.setPermissionButtonList(item.children)
        // }

        this.permissionButtonList.push({
          catalogName: item.catalogName,
          path: item.address,
          hasPri: item.hasPri,
          status: item.status,
          code: item.code,
        })
      })
    },
  },
}
</script>

<style lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  background: url(./../../assets/login-bg.png) center center no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
  .login-logo {
    position: absolute;
    top: 19%;
    left: 19%;
    font-size: 25px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #ffffff;
    svg {
      font-size: 35px;
      margin-right: 4px;
    }
  }
  .login-form {
    width: 356px;
    height: 350px;
    background: #ffffff;
    border-radius: 4px;
    margin-right: 19%;
    overflow: hidden;
    .login-title {
      font-size: 22px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #10a6dd;
      height: 66px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #eef2f7;
    }
    .login-box {
      padding: 51px 21px;
      .el-form-item {
        &:nth-child(2) {
          margin-bottom: 19px;
        }
        margin-bottom: 33px;
        .login-extent {
          display: flex;
          color: #a8a8a8;
          justify-content: space-between;
          .el-checkbox {
            color: #a8a8a8 !important;
            .el-checkbox__input.is-checked + .el-checkbox__label {
              color: #a8a8a8;
            }
          }
        }
      }
    }

    .submit-btn {
      width: 100%;
    }
  }
}
</style>
